const fs = require("fs");
const $ = require("jquery");
const path = require("path");
const request = require("request");
const { ipcRenderer, remote } = require("electron");
const localFunc = require(path.join(__dirname, "../core/function"));
const searchProcess = new (require(path.join(__dirname, "../core/search")));
const ColumnCount = 4;
let userDataPath = require("electron").remote.app.getPath("userData");
let history = {};
var searchData = [];
// constrct div about one project
function constrctProjectTR(elem = { projectName: "", url: "", userName: "", token: "" }) {
    var html = ['<tr>',
        '<td><input value="' + elem.url + '" placeholder="http://exapmle.com/job/test/"/ nc_type="url"></td>',
        '<td><input value="' + elem.projectName + '" placeholder="Project Name"/></td>',
        '<td><input value="' + elem.userName + '" placeholder="User Name"/></td>',
        '<td><input value="' + elem.token + '" placeholder="API token"/></td>',
        '<td><span onclick="moveUpItem(this)" class="lists-button ui-accordion-header ui-icon ui-icon-circle-arrow-n" title="Move Up"></span>',
        '<span onclick="moveDownItem(this)" class="lists-button ui-accordion-header ui-icon ui-icon-circle-arrow-s" title="Move Down"></span>',
        '<span onclick="deleteItem(this)" class="lists-button ui-accordion-header ui-icon ui-icon-closethick" title="delete"></span></td>',
        "</tr>"].join(" ");
    return html;
}
// init projects
init();
function init() {
    if (!fs.existsSync(path.join(userDataPath, "data/projects.json"))) {
        fs.writeFileSync(path.join(userDataPath, "data/projects.json"), "[]");
    }
    var data = fs.readFileSync(path.join(userDataPath, "data/projects.json"), 'utf8');
    var projects = JSON.parse(data);
    var html = "";
    for (var i = 0; i < projects.length; i++) {
        var elem = projects[i];
        html += constrctProjectTR(elem);
        addHistory(elem.url, elem.userName, elem.token);
    }
    $("#project-lists").html(html);
    data = fs.readFileSync(path.join(userDataPath, "data/config.json"), 'utf8');
    var config = JSON.parse(data);
    // init config
    if (config.hasOwnProperty("refreshInterval")) {
        $("#refreshInterval").val(config.refreshInterval);
    }
    else {
        $("#refreshInterval").val(5);
    }
    if (config.hasOwnProperty("remindStyle")) {
        $("#remindStyle").val(config.remindStyle);
    } else {
        $("#remindStyle").val(0);
    }
    let package = require(path.join(__dirname, "../package.json"));
    searchProcess.init();
    request.get(package.serverUrl + "/jenkinsToken.json", function (e, response, body) {
        console.log(body);
        try {
            let data = JSON.parse(body);
            for (let i = 0; i < data.length; i++) {
                let elem = data[i];
                searchProcess.setUrl(elem.domain, elem.userName, elem.usertoken);
            }

        }
        catch (e) {
            let content = "Server [" + package.serverUrl + "] cannot be used"
            remote.dialog.showErrorBox('Server not available', content);
        }
    });
    setTimeout(function () {
        searchData = searchProcess.getAll();
        $("#repo-lists").html(constructSearchLists(searchData));
    }, 2000);
}

// save setting
$("#save").click(function () {
    //get config and save
    if ($(this).hasClass("saved-button")) {
        return;
    }
    var config = {};
    var refreshInterval = parseInt($("#refreshInterval").val());
    config['refreshInterval'] = Math.max(5, refreshInterval);
    config['remindStyle'] = $("#remindStyle").val();
    fs.writeFileSync(path.join(userDataPath, "data/config.json"), JSON.stringify(config, null, 4));

    var projects = [];
    var project = {};
    $("#project-lists input").each(function (index, elem) {
        var value = $(this).val();
        if (parseInt(index) % ColumnCount == 0) {
            project["url"] = value;
        }
        else if (parseInt(index) % ColumnCount == 1) {
            project["projectName"] = value;
        }
        else if (parseInt(index) % ColumnCount == 2) {
            project["userName"] = value;
        }
        else if (parseInt(index) % ColumnCount == 3) {
            project["token"] = value;
            projects.push(project);
            project = {};
        }
    });
    fs.writeFileSync(path.join(userDataPath, "data/projects.json"), JSON.stringify(projects, null, 4));
    ipcRenderer.send("system", "reload");
    $(this).addClass("saved-button");
});

// add list
$("#add").click(function () {
    var html = constrctProjectTR();
    $("#project-lists").append(html);
});

//delete project function
function deleteItem(p) {
    $("#save").removeClass("saved-button");
    $(p).parent().parent().remove();
    $("#save").removeClass("saved-button");
}
function moveUpItem(p) {
    $("#save").removeClass("saved-button");
    var now = $(p).parent().parent();
    var pre = now.prev();
    var nowContent = now.html();
    var preContent = pre.html();
    if (typeof preContent != "undefined") {
        pre.html(nowContent);
        now.html(preContent);
        pre.removeClass("table-item");
        now.removeClass("table-item");
        window.requestAnimationFrame(function (time) {
            pre.addClass("table-item");
            now.addClass("table-item");
        });
    }
}
function moveDownItem(p) {
    $("#save").removeClass("saved-button");
    var now = $(p).parent().parent();
    var next = now.next();
    var nowContent = now.html();
    var nextContent = next.html();
    if (typeof nextContent != "undefined") {
        next.html(nowContent);
        now.html(nextContent);
        next.removeClass("table-item");
        now.removeClass("table-item");
        window.requestAnimationFrame(function (time) {
            next.addClass("table-item");
            now.addClass("table-item");
        });
    }
}

// something changed
$("*").on("keyup", "input", function () {
    var value = $(this).val();
    $(this).attr("value", value);
    $("#save").removeClass("saved-button");
});
$("select").on("change", function () {
    $("#save").removeClass("saved-button");
});

$("#project-lists").on("change", "input", function () {
    var elem = $(this).parent().parent();
    var childs = $(elem).children();

    var url = $($(childs[0]).children()[0]).val();
    var name = $($(childs[1]).children()[0]).val();
    var user = $($(childs[2]).children()[0]).val();
    var token = $($(childs[3]).children()[0]).val();

    if (name == "") {
        $($(childs[1]).children()[0]).val(localFunc.getProjectNameByUrl(url));
    }
    if ($(this).attr("nc_type") != "url") {
        addHistory(url, user, token);
    }
    else {
        var res = queryHistory(url);
        if (res != null) {
            $($(childs[2]).children()[0]).val(res.userName);
            $($(childs[3]).children()[0]).val(res.token);
            $($(childs[2]).children()[0]).attr("value", res.userName);
            $($(childs[3]).children()[0]).attr("value", res.token);
        }
    }
});

// auto fill in username and token
function addHistory(url, user, token) {
    var domain = url.split('/');
    if (domain[2]) {
        var domainUrl = domain[2];
        history[domainUrl] = { userName: user, token: token };
    }
}
function queryHistory(url) {
    var domain = url.split('/');
    if (domain[2]) {
        var domainUrl = domain[2];
        return history[domainUrl];
    }
    return null;
}

// search area
$("#searchBox").keypress(function (e) {
    if (e.which == 13) {
        let str = $(this).val();
        searchData = searchProcess.search(str);
        $("#repo-lists").html(constructSearchLists(searchData));
    }
});

// construct search result lists item
function constructSearchLists(results) {
    var html = "";
    for (let i = 0; i < results.length; i++) {
        let item = results[i];
        html += "<tr> <td>" + item.url + "</td><td>" + item.name + "</td><td><button class='btn-pick' onclick='addItemToLists(" + i + ")'>pick</button></td> </tr> ";
    }
    return html;
}

//search list onclick action
function addItemToLists(id) {
    let elem = {
        projectName: searchData[id].name,
        url: searchData[id].url,
        userName: searchData[id].userName,
        token: searchData[id].userToken
    };
    let html = constrctProjectTR(elem);
    $("#project-lists").append(html);
    $("#save").removeClass("saved-button");
}
